/*
 * Copyright (C) 2021 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_i2c.h"

#include "ssd1306.h"
#include "aht20.h"

void Aht20TestTask(void)
{
    char str1[16];
    char str2[16];
    uint32_t retval = 0;

    retval = AHT20_Calibrate();
    printf("AHT20_Calibrate: %d\r\n", retval);

    float temp = 0.0, humi = 0.0;
    retval = AHT20_StartMeasure();
    printf("AHT20_StartMeasure: %d\r\n", retval);

    while (1) {
        retval = AHT20_GetMeasureResult(&temp, &humi);
        printf("AHT20_GetMeasureResult: %d, temp = %.2f, humi = %.2f\r\n", retval, temp, humi);

        if(HI_ERR_SUCCESS == retval) {
            snprintf(str1, sizeof(str1), "temp: OK");
            snprintf(str2, sizeof(str2), "humi: OK");
        } else {
            snprintf(str1, sizeof(str1), "temp: --");
            snprintf(str2, sizeof(str2), "humi: --");
        }

        ssd1306_Fill(Black);
        ssd1306_SetCursor(5, 5);
        ssd1306_DrawString("AHT20", Font_11x18, White);
        ssd1306_SetCursor(5, 5+18+3);
        ssd1306_DrawString(str1, Font_7x10, White);
        ssd1306_SetCursor(5, 5+18+3+10+3);
        ssd1306_DrawString(str2, Font_7x10, White);
        ssd1306_SetCursor(5, 5+18+5+10+5+10);
        ssd1306_DrawString("UP          DOWN", Font_7x10, White); 
        ssd1306_UpdateScreen();

        if(HI_ERR_SUCCESS == retval) {
            break;
        }
        usleep(100*1000);
    }
}

void Aht20TestEntry(void)
{
    //I2C0 is already inited in main task
#if 1
    Aht20TestTask();
#else
    //osPriorityAboveNormal[32], osPriorityNormal[24]
    //{.name, .attr_bits, .cb_mem, .cb_size, .stack_mem, .stack_size, .priority, .tz_module, .reserved}
    osThreadAttr_t attr = {"Aht20TestTask", 0, NULL, 0, NULL, 1024*10, 24, 0, 0};
    osThreadId_t taskId = osThreadNew((osThreadFunc_t)Aht20TestTask, NULL, &attr);
    if (taskId == NULL) {
        printf("[Aht20TestEntry] Falied to create %s!\n", attr.name);
    }
#endif
}

